package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"store-pro/models"
	"store-pro/pkg"
)

type ShopController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户或者密码为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User
	var err error
	err = models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if user.Password != pkg.Md5str1(password) {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "登入成功",
			Data: nil,
		}
		c.ServeJSON()
	}
} //登录
func (c *ShopController) Add() {
	shopName := c.GetString("shopName")
	rent, _ := c.GetFloat("rent")
	place, _ := c.GetInt("place")
	shop := models.Shop{
		ShopName: shopName,
		Rent:     rent,
		Place:    place,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	var shop []models.Shop
	err := models.DB.Find(&shop).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: shop,
		}
		c.ServeJSON()
		return
	}

}
